from flask import Blueprint, request
from flask import current_app
from models.event import EventModel
from models.img import ImageModel
from blueprints.images import delete_img_update, delete_img_delete
from utils import restful
from exts import db
from datetime import datetime


bp = Blueprint('event', __name__, url_prefix='/event')


# 1、根据id获取活动信息
@bp.route('/get/<int:eid>', methods=['GET'])
def get_event(eid):
    event = EventModel.query.get(eid)
    if event:
        return restful.ok(data={'event': event.to_dict()})
    return restful.params_error()


# 2、根据页数获取活动信息
@bp.route('/getPage/<int:page>', methods=['GET'])
def get_events_page(page):
    res = []
    page_size = current_app.config['EVENT_PAGE_SIZE']
    offset = (page-1) * page_size
    events = EventModel.query.offset(offset).limit(page_size).all()
    for e in events:
        res.append(e.to_dict())
    return restful.ok(data={'events': res})


# 3、创建新的活动信息
@bp.route('/create', methods=['POST'])
def create_events():
    data = request.json
    print(data)
    title = data.get('title')
    details = data.get('details')
    begin_time = data.get('begin_time')
    finish_time = data.get('finish_time')
    location = data.get('location')
    if title and details and begin_time and finish_time and location:
        begin_time = str_p_datetime(begin_time)
        finish_time = str_p_datetime(finish_time)
        event = EventModel(title=title, details=details, begin_time=begin_time, finish_time=finish_time, location=location)
        if data.get('cover_img'):
            event.cover_img = data.get('cover_img')
        db.session.add(event)
        db.session.flush()
        images = []
        if data.get('imgs'):
            for u in data.get('imgs'):
                if u:
                    image = ImageModel(article_id=event.event_id, type='event', url=u)
                    images.append(image)
        db.session.add_all(images)
    else:
        return restful.params_error()
    db.session.commit()
    return restful.ok(message='上传成功!')


# 4、更新活动信息
@bp.route('/update/<int:event_id>',  methods=['POST'])
def update_events(event_id):
    data = request.json
    data['event'] = event_id
    print(data)
    old_event = EventModel.query.get(event_id)
    if old_event:
        old_event.title = data.get('title') if data.get('title') else old_event.title
        old_event.details = data.get('details') if data.get('details') else old_event.details
        old_event.cover_img = data.get('cover_img') if data.get('cover_img') else old_event.cover_img
        old_event.begin_time = str_p_datetime(data.get('begin_time')) if data.get('begin_time') else old_event.begin_time
        old_event.finish_time = str_p_datetime(data.get('finish_time')) if data.get('finish_time') else old_event.finish_time
        old_event.location = data.get('location') if data.get('location') else old_event.location
        db.session.commit()
        # 删除图片，数据库和文件，调用 images.delete_img_update
        delete_img_update(event_id, 'event', data.get('imgs'), data.get('imgList'))
    else:
        return restful.params_error()
    return restful.ok(message="上传成功",data=str(event_id))


# 5、删除活动信息
@bp.route('/delete/<int:event_id>', methods=['DELETE'])
def delete_blog(event_id):
    old_event = EventModel.query.get(event_id)
    # 2、删除图片
    delete_img_delete(event_id, 'event')
    # 3、提交事务
    db.session.delete(old_event)
    db.session.commit()
    return restful.ok(message='删除成功')


def str_p_datetime(string):
    return datetime.strptime(string, '%Y-%m-%d %H:%M:%S')